var fs = require('fs')
var path = require('path')

var adminPath = path.resolve('./src/routes/admin');
transform(adminPath);
var normalPath = path.resolve('./src/routes/normal');
transform(normalPath);

fs.readFile('./src/routes/menuRoute.js', (readError, data) => {
  if (readError) {
    return console.error(readError);
  }
  let content = data.toString();
  content = content.replace('getComponent={targetItem.components}', 'component={targetItem.components}');
  fs.writeFile('./src/routes/menuRoute.js', content, (writeError) => {
    if (writeError) {
      return console.error(writeError);
    }
  });
});

function transform(filePath){
  fs.readdir(filePath, (readDirError,files) => {
    if(readDirError){
      console.error(readDirError)
    } else {
      files.forEach(filename => {
        var filedir = path.join(filePath, filename);
        fs.stat(filedir, (statError, stats) => {
          if(statError){
            console.error(statError);
          } else {
            var isFile = stats.isFile();//是文件
            var isDir = stats.isDirectory();//是文件夹
            if(isFile){
              fs.readFile(filedir,(readError, data) => {
                if (readError) {
                  return console.error(readError);
                }
                let content = data.toString();
                content = content.replace(/const\s*(\S*)\s*=([\s\S])*?require\.ensure([\s\S])*?["']{1}(\S*)["']{1}\)\.([\s\S])*?\)\n*?\}/g, (target, $1, $2, $3, $4) => {
                  return `import ${$1} from "${$4}"`;
                });
                fs.writeFile(filedir, content, (writeError) => {
                  if (writeError) {
                    return console.error(writeError);
                  }
                });
              });
            }
            if(isDir){
              transform(filedir);
            }
          }
        })
      });
    }
  });
}
